package authentication

import (
	"errors"
	"shi_project/main/database"
	"strconv"

	"github.com/gin-gonic/gin"
)

type PermissionCode struct {
	Name           string `json:"name"`
	PermissionType string `json:"type"`
}

var (
	MassEmail           = PermissionCode{Name: "群发邮件", PermissionType: "按钮"}
	PermissionPage      = PermissionCode{Name: "权限管理页", PermissionType: "菜单"}
	CommunicationModule = PermissionCode{Name: "交流模块", PermissionType: "菜单"}
)

// func getUserPermissions(id string) []string {

// 	return []string{MassEmail}
// }

// 判断当前用户是否有权限 传一个登录用户,传一个权限 有权限返回nil,无权限返回error
func IsPass(c *gin.Context, p PermissionCode) error {
	val, exists := c.Get("userId")
	if !exists {
		return errors.New("获取用户ID失败")
	}
	userID, err := strconv.ParseInt(val.(string), 10, 64)
	if userID == 1 {
		return nil //超级管理员直接放行
	}
	data, err := database.GetUserInfo(userID)
	if err != nil {
		return err
	}
	list, err := database.GetUserPermissionsListByTree(data)
	if err != nil {
		return err
	}
	for _, v := range list {
		if v.Name == p.Name && v.Type == p.PermissionType {
			// 有权限返回nil
			return nil
		}
	}
	return errors.New("无权限访问")
}
